//
//  ZhuceViewController.m
//  Contractor
//
//  Created by 金鑫 on 16/5/11.
//  Copyright © 2016年 star j. All rights reserved.
//

#import "ZhuceViewController.h"
#import "CustomTextField.h"
#import "AFHTTPRequestOperationManager.h"
#import "CodeWithDES.h"
#import "CONST.h"

@interface ZhuceViewController ()<UITextFieldDelegate>
{
    CustomTextField *account ;
    CustomTextField *password ;
    CustomTextField *teacherNumber ;
    UIButton *yanzhengBtn ;
    UIButton *zhuceBtn ;
    
}
@end

@implementation ZhuceViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor] ;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.edgesForExtendedLayout = UIRectEdgeBottom | UIRectEdgeLeft | UIRectEdgeRight;
    self.navigationItem.title = @"注册" ;
    [self createView] ;
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO ;
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES ;
}


- (void)createView
{
    //账号输入框
    account = [self createTextField:@"手机" withFrame:CGRectMake(20, 0, __kScreenWidth-90, 50) imageName:@"register_username_normal_icon.png"] ;
    //验证按钮
    yanzhengBtn = [[UIButton alloc] initWithFrame:CGRectMake(__kScreenWidth - 90, account.frame.origin.y + 5, 80, 40)] ;
    [yanzhengBtn setTitle:@"  验证码  " forState:UIControlStateNormal] ;
    yanzhengBtn.backgroundColor = [UIColor blueColor] ;
    yanzhengBtn.layer.cornerRadius = 5 ;
    [yanzhengBtn addTarget:self action:@selector(yanzheng) forControlEvents:UIControlEventTouchUpInside] ;
    [self.view addSubview:yanzhengBtn] ;
    //验证码
    CGRect passwordRect = CGRectMake(20, account.frame.origin.y + account.frame.size.height, __kScreenWidth-40, 50) ;
    password = [self createTextField:@"手机验证码" withFrame:passwordRect imageName:@"register_sms_auth_code_normal_icon.png"] ;
    //推荐师傅号
    CGRect numRect = CGRectMake(20, password.frame.origin.y + password.frame.size.height, __kScreenWidth-40, 50) ;
    teacherNumber = [self createTextField:@"推荐师傅号码（可填）" withFrame:numRect imageName:@"register_recommend_number_normal_icon.png"] ;
    //分割线
    CGRect lineRect1 = CGRectMake(20, account.frame.origin.y + account.frame.size.height, __kScreenWidth-30, 1) ;
    CGRect lineRect2 = CGRectMake(20, password.frame.origin.y + password.frame.size.height, __kScreenWidth-30, 1) ;
    CGRect lineRect3 = CGRectMake(20, password.frame.origin.y + password.frame.size.height + 50, __kScreenWidth-30, 1) ;
    UIImageView *line1 = [[UIImageView alloc] initWithFrame:lineRect1] ;
    [line1 setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    UIImageView *line2 = [[UIImageView alloc] initWithFrame:lineRect2] ;
    [line2 setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    UIImageView *line3 = [[UIImageView alloc] initWithFrame:lineRect3] ;
    [line3 setImage:[UIImage imageNamed:@"layout_small_line_bg.png"]] ;
    
    [self.view addSubview:account] ;
    [self.view addSubview:password] ;
    [self.view addSubview:teacherNumber] ;
    [self.view addSubview:line1] ;
    [self.view addSubview:line2] ;
    [self.view addSubview:line3] ;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer
                                                     alloc] initWithTarget:self action:@selector(hideKeyBoard:)];
    tapGestureRecognizer.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer: tapGestureRecognizer];   //只需要点击非文字输入区域就会响应hideKeyBoard
    
    zhuceBtn = [UIButton buttonWithType:UIButtonTypeCustom] ;
    zhuceBtn.frame = CGRectMake(20, teacherNumber.frame.origin.y + teacherNumber.frame.size.height+50, __kScreenWidth - 40, 40) ;
    [zhuceBtn setTitle:@"立即注册" forState:UIControlStateNormal] ;
    zhuceBtn.backgroundColor = [UIColor blueColor] ;
    zhuceBtn.layer.cornerRadius = 10.0f ;
    [zhuceBtn addTarget:self action:@selector(zhuce) forControlEvents:UIControlEventTouchUpInside] ;
    [self.view addSubview:zhuceBtn] ;
}

- (CustomTextField *)createTextField:(NSString *)title withFrame:(CGRect)rect imageName:(NSString *)name
{
    CustomTextField *textfield = [[CustomTextField alloc] initWithFrame:rect] ;
    [textfield setBackgroundColor:[UIColor clearColor]] ;
    textfield.placeholder = title ;
    textfield.delegate = self ;
    textfield.keyboardType = UIKeyboardTypePhonePad ;
    
    //账号最左侧图片
    UIImageView *leftImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 24, 24)] ;
    [leftImage setImage:[UIImage imageNamed:name]] ;
    textfield.leftView = leftImage ;
    textfield.leftViewMode = UITextFieldViewModeAlways ;
    textfield.textAlignment = NSTextAlignmentLeft ;
    textfield.autocapitalizationType = UITextAutocapitalizationTypeNone ;//首字母不大写
    textfield.autocorrectionType = UITextAutocorrectionTypeNo ;//是否纠错
    return textfield ;
}


#pragma mark - textfieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder] ;
    
    return YES ;
}

#pragma mark - 收起键盘
- (void)hideKeyBoard:(id)sender
{
    [account  resignFirstResponder] ;
    [password resignFirstResponder] ;
    [teacherNumber resignFirstResponder] ;
}

#pragma mark - 立即注册
- (void)zhuce
{
    [account  resignFirstResponder] ;
    [password resignFirstResponder] ;
    [teacherNumber resignFirstResponder] ;
    NSLog(@"注册") ;
    NSNumber *cmd = [[NSNumber alloc] initWithInt:1] ;
    NSNumber *authgroup = [[NSNumber alloc] initWithInt:3] ;
    
    NSDictionary *jsondic = @{@"username":account.text,
                              @"password":@"123456",
                              @"authgroup":authgroup,
                              @"recommond_phone":teacherNumber.text,
                              @"verify":password.text} ;
    NSLog(@"注册json:%@",jsondic) ;
    
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"jsonstr":jsonstr};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if ([account.text isEqualToString:@""]) {
        zhuceBtn.enabled = NO ;
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 120)/2, __kScreenHeight - 70, 120, 40)] ;
        [errorbtn setTitle:@"用户名不能为空" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else if ([password.text isEqualToString:@""]){
        zhuceBtn.enabled = NO ;
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 120)/2, __kScreenHeight - 70, 120, 40)] ;
        [errorbtn setTitle:@"验证码不能为空" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    else{
        [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            //解密并解析json数据，将json转成字典
            NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
            decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
            NSLog(@"decodeStr:%@",decodeStr) ;
            NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
            id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
            if ([result isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dic = result ;
                NSLog(@"dic:%@",dic) ;
                if ([dic[@"status"] integerValue] <= 0) {
                    zhuceBtn.enabled = NO ;
                    UILabel *label = [[UILabel alloc] init] ;
                    label.font = [UIFont systemFontOfSize:14.0f] ;
                    label.text = dic[@"msg"] ;
                    label.textColor = [UIColor whiteColor] ;
                    label.textAlignment = NSTextAlignmentCenter ;
                    label.backgroundColor = [UIColor blackColor] ;
                    label.alpha = 0.8 ;
                    label.layer.cornerRadius = 10 ;
                    label.layer.masksToBounds = YES ;
                    label.frame = CGRectMake((__kScreenWidth - 200)/2, __kScreenHeight - 70, 200, 40) ;
                    label.numberOfLines = 0;
                    [[UIApplication sharedApplication].keyWindow addSubview:label] ;
                    [self performSelector:@selector(clearbtn:) withObject:label afterDelay:2.0] ;

                }
                else
                {
                    zhuceBtn.enabled = NO ;
                    UILabel *label = [[UILabel alloc] init] ;
                    label.font = [UIFont systemFontOfSize:14.0f] ;
                    label.text = dic[@"msg"] ;
                    label.textColor = [UIColor whiteColor] ;
                    label.textAlignment = NSTextAlignmentCenter ;
                    label.backgroundColor = [UIColor blackColor] ;
                    label.alpha = 0.8 ;
                    label.layer.cornerRadius = 10 ;
                    label.layer.masksToBounds = YES ;
                    label.frame = CGRectMake((__kScreenWidth - 200)/2, __kScreenHeight - 70, 200, 40) ;
                    label.numberOfLines = 0;
                    [[UIApplication sharedApplication].keyWindow addSubview:label] ;
                    [self performSelector:@selector(clearbtn:) withObject:label afterDelay:2.0] ;
                    NSNumber *type = [[NSNumber alloc] initWithInt:1] ;
                    NSDictionary *jsondic = @{@"username":account.text,
                                              @"password":@"",
                                              @"clienttype":type} ;
                    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults] ;
                    [userDefault setValue:jsondic forKey:@"loginuserinfo"] ;
                    [self.navigationController popViewControllerAnimated:NO] ;
                }
            }
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            
        }] ;
    }
}

#pragma mark - 请求验证码
- (void)yanzheng
{
    [account  resignFirstResponder] ;
    [password resignFirstResponder] ;
    [teacherNumber resignFirstResponder] ;
    NSLog(@"test") ;
    NSNumber *cmd = [[NSNumber alloc] initWithInt:21] ;
    
    NSDictionary *jsondic = @{@"username": account.text} ;
    NSString *jsonstr =  [CodeWithDES encodeWithDic:jsondic] ;
    NSDictionary *parameters = @{@"cmd":cmd,@"jsonstr":jsonstr};
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    if ([self valiMobile:account.text] == YES) {
        [manager POST:getAppJson parameters:parameters success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            //解密并解析json数据，将json转成字典
            NSString *decodeStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding] ;
            decodeStr = [CodeWithDES decodeWithStr:decodeStr] ;
            NSLog(@"decodeStr:%@",decodeStr) ;
            NSData *decodeData = [decodeStr dataUsingEncoding:NSUTF8StringEncoding] ;
            id result = [NSJSONSerialization JSONObjectWithData:decodeData options:NSJSONReadingMutableContainers error:nil] ;
            if ([result isKindOfClass:[NSDictionary class]])
            {
                NSDictionary *dic = result ;
                NSLog(@"dic:%@",dic) ;
                [self timenum] ;
            }
        } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
            
        }] ;
    }
    else
    {
        yanzhengBtn.enabled = NO ;
        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 100)/2, __kScreenHeight - 70, 100, 40)] ;
        [errorbtn setTitle:@"手机号码错误" forState:UIControlStateNormal] ;
        errorbtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:14.0f] ;
        errorbtn.layer.cornerRadius = 10 ;
        errorbtn.backgroundColor = [UIColor blackColor] ;
        errorbtn.alpha = 0.8 ;
        //[self.view addSubview:errorbtn] ;
        [[UIApplication sharedApplication].keyWindow addSubview:errorbtn] ;
        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
    }
    
    
//    if ([account.text isEqualToString:@""]) {
//        UIButton *errorbtn = [[UIButton alloc] initWithFrame:CGRectMake((__kScreenWidth - 150)/2, __kScreenHeight - 70, 150, 40)] ;
//        [errorbtn setTitle:@"手机号码错误" forState:UIControlStateNormal] ;
//        errorbtn.layer.cornerRadius = 10 ;
//        errorbtn.backgroundColor = [UIColor blackColor] ;
//        errorbtn.alpha = 0.8 ;
//        [self.view addSubview:errorbtn] ;
//        [self performSelector:@selector(clearbtn:) withObject:errorbtn afterDelay:2.0] ;
//    }
}

#pragma mark - 验证码倒计时
- (void)timenum
{
    __block int timeout=60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            yanzhengBtn.enabled = YES ;
            dispatch_source_cancel(_timer);
            //dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                yanzhengBtn.titleLabel.text = @"  验证码  " ;
            });
        }else{
            yanzhengBtn.enabled = NO ;
//            int minutes = timeout / 60;
//            int seconds = timeout % 60;
            NSString *strTime = nil ;
            if (timeout >= 10) {
                strTime = [NSString stringWithFormat:@" 还剩%lds",(long)timeout];
            }
            else
            {
                strTime = [NSString stringWithFormat:@"  还剩%lds",(long)timeout];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                yanzhengBtn.titleLabel.text = strTime ;
                //zhuceBtn.titleLabel.font = [UIFont fontWithName:@"AvenirLTStd-Light" size:16.0f] ;
            });
            timeout--;
            
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 判断是否是电话号码
- (BOOL)valiMobile:(NSString *)mobile{
    if (mobile.length < 11)
    {
        return NO;
    }
    else{
        /**
         * 移动号段正则表达式
         */
        NSString *CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\\d{8}|(1705)\\d{7}$";
        /**
         * 联通号段正则表达式
         */
        NSString *CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\\d{8}|(1709)\\d{7}$";
        /**
         * 电信号段正则表达式
         */
        NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\\d{8}$";
        NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
        BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
        NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
        BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
        NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
        BOOL isMatch3 = [pred3 evaluateWithObject:mobile];
        
        if (isMatch1 || isMatch2 || isMatch3) {
            return YES;
        }else{
            return NO;
        }
    }
}

- (void)clearbtn:(id)sender
{
    yanzhengBtn.enabled = YES ;
    zhuceBtn.enabled = YES ;
    [sender removeFromSuperview] ;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
